package ar.com.sectorwine.controllers;

import java.security.Principal;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import ar.com.sectorwine.dto.StockDTO;
import ar.com.sectorwine.dto.StockDTOMapper;
import ar.com.sectorwine.entities.Stock;
import ar.com.sectorwine.services.StockService;
import ar.com.sectorwine.services.UsuarioService;

/**
 * Handles requests for the application home page.
 */
@Controller
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class StockController {

	@Autowired
	private StockService stockService;
	@Autowired
	private Validator validator;
	@Autowired
	private StockDTOMapper stockDTOMapper;

	private static final Logger logger = LoggerFactory
			.getLogger(StockController.class);

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "stock_alta", method = RequestMethod.GET)
	public String alta_stock(Locale locale, Model model, @RequestParam String id) {

		logger.info("Welcome home! the client locale is " + locale.toString());

		StockDTO stock = new StockDTO();
		stock.setId(Long.parseLong(id));

		model.addAttribute("variedades",
				(List<String>) stockService.getParametro("variedad"));
		model.addAttribute("dtoStock", stock);

		return "stocks/stocks_alta";
	}

	@RequestMapping(value = "stock_alta", method = RequestMethod.POST)
	public ModelAndView create_stock(
			@Valid @ModelAttribute("dtoStock") StockDTO stockDTO,
			BindingResult result, SessionStatus status, Principal principal) {
		logger.info("controller");
		Stock stock = stockDTOMapper.obtenerObjetoDelDominioDesdeDTO(stockDTO);

		Set<ConstraintViolation<StockDTO>> failures = validator
				.validate(stockDTO);

		if (failures.size() == 0) {
			if (stock != null) {
				stockService.crearStock(stockDTO.getId(), stock);
				status.setComplete();
				ModelAndView mav = new ModelAndView("home");
				return mav;
			} else {
				ModelAndView mav = new ModelAndView("stocks/stocks_alta");
				mav.addObject("variedades",
						(List<String>) stockService.getParametro("variedad"));
				mav.addObject("dtoStock", stockDTO);
				return mav;
			}
		} else {
			ModelAndView mav = new ModelAndView("stocks/stocks_alta");
			mav.addObject("variedades",
					(List<String>) stockService.getParametro("variedad"));
			mav.addObject("dtoStock", stockDTO);
			for (Object o : failures) {
				logger.info(o.toString());
			}
			return mav;
		}

	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "stocks_listar", method = RequestMethod.GET)
	public ModelAndView lista(Locale locale, Model model, Principal principal, @RequestParam String id) {

		ModelAndView mav = new ModelAndView("stocks/stocks_listar");

		mav.addObject("mis_stocks",stockService.buscarStockEmpresa(Long.parseLong(id)));
		return mav;
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "stocks_detalle", method = RequestMethod.GET)
	public ModelAndView modificar(Locale locale, @RequestParam String id,
			Model model) {

		logger.info("Welcome home! the client locale is " + locale.toString());

		ModelAndView mav = new ModelAndView("stocks/stocks_detalle");

		Stock stock_buscado = stockService.getStock(id);
		mav.addObject("stock", stock_buscado);
		return mav;
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "stocks_modificar", method = RequestMethod.GET)
	public String modificar_stock(Locale locale, Model model,
			@RequestParam String id) {

		logger.info("Welcome home! the client locale is " + locale.toString());

		Stock stock = stockService.getStock(id);
		;

		model.addAttribute("variedades",
				(List<String>) stockService.getParametro("variedad"));
		model.addAttribute("stock", stock);

		return "stocks/stocks_modificar";
	}

	@RequestMapping(value = "stocks_modificar", method = RequestMethod.POST)
	public ModelAndView modificar(
			@Valid @ModelAttribute("stock") StockDTO stockDTO,
			BindingResult result, SessionStatus status) {

		logger.info("controller");
		Stock stock = stockDTOMapper.obtenerObjetoDelDominioDesdeDTO(stockDTO);

		Set<ConstraintViolation<StockDTO>> failures = validator
				.validate(stockDTO);

		if (failures.size() == 0) {
			if (stock != null) {
				stockService.modificarStock(stock);
				status.setComplete();
				ModelAndView mav = new ModelAndView("home");
				mav.addObject("stock", stockDTO);
				return mav;
			} else {
				ModelAndView mav = new ModelAndView("stocks/stocks_modificar");
				mav.addObject("stock", stockDTO);
				return mav;
			}
		} else {
			ModelAndView mav = new ModelAndView("stocks/stocks_modificar");
			mav.addObject("stock", stockDTO);
			for (Object o : failures) {
				logger.info(o.toString());
			}
			return mav;
		}

	}

	@RequestMapping(value = "stock_baja", method = RequestMethod.POST)
	public ModelAndView darBajaLogica(Locale locale, @RequestParam String id,
			Model model) {

		logger.info("controller");

		ModelAndView mav = new ModelAndView("home");
		mav.addObject("resultado", stockService.bajaStock(id));
		return mav;
	}

}